<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>旅行数据分析系统</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
</head>
<body>
<div class="header">
    <h1>旅行数据分析系统</h1>
    <p>基于去哪儿网旅行数据的可视化分析</p>
</div>

<div class="main-container">
    <div class="button-group">
        <button onclick="showWordCloud()">🌌 旅行关键词云</button>
        <button onclick="showChart('popularCities')">🏙️ 热门城市</button>
        <button onclick="showChart('travelMonth')">📅 旅游月份</button>
        <button onclick="showChart('travelCost')">💰 人均花费</button>
        <button onclick="showChart('travelDays')">⏱️ 旅游天数</button>
        <button onclick="showChart('photoAnalysis')">📸 照片数量</button>
        <button onclick="showChart('companionType')">👥 同伴类型</button>
    </div>

    <div class="chart-container">
        <canvas id="chartCanvas"></canvas>
    </div>
</div>

<div class="footer">
    <p>数据来源：去哪儿旅行网 | 可视化分析工具</p>
</div>

<script>
    let currentChart = null;

    function showWordCloud() {
    fetch('/get_wordcloud')
        .then(res => res.json())
        .then(data => {
            const popup = window.open("", "词云", "width=900,height=700");
            popup.document.write(`<img src="data:image/png;base64,${data.image}"
                                style="max-width:100%">`);
        });
}

    function showChart(option) {
        fetch(`/get_data?option=${option}`)
            .then(response => response.json())
            .then(data => {
                const ctx = document.getElementById('chartCanvas').getContext('2d');

                // 销毁之前的图表
                if (currentChart) {
                    currentChart.destroy();
                }

                // 设置图表标题
                const titles = {
                    'popularCities': '热门旅游城市TOP10',
                    'travelMonth': '旅游月份分布',
                    'travelCost': '人均花费分布',
                    'travelDays': '旅游天数分布',
                    'photoAnalysis': '照片数量分布',
                    'companionType': '旅游同伴类型'
                };

                currentChart = new Chart(ctx, {
                    type: 'pie',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: titles[option],
                            data: data.values,
                            backgroundColor: getChartColors(data.labels.length),
                            borderColor: '#ffffff',
                            borderWidth: 2
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            title: {
                                display: true,
                                text: titles[option],
                                font: {
                                    size: 18,
                                    family: 'Microsoft YaHei'
                                },
                                padding: {
                                    top: 10,
                                    bottom: 20
                                }
                            },
                            legend: {
                                position: 'right',
                                labels: {
                                    font: {
                                        size: 14,
                                        family: 'Microsoft YaHei'
                                    },
                                    padding: 20,
                                    usePointStyle: true,
                                    pointStyle: 'circle'
                                }
                            },
                            tooltip: {
                                bodyFont: {
                                    size: 14,
                                    family: 'Microsoft YaHei'
                                },
                                callbacks: {
                                    label: function (context) {
                                        const label = context.label || '';
                                        const value = context.raw || 0;
                                        const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                        const percentage = Math.round((value / total) * 100);
                                        return `${label}: ${value} (${percentage}%)`;
                                    }
                                }
                            }
                        },
                        animation: {
                            animateScale: true,
                            animateRotate: true
                        }
                    }
                });
            })
            .catch(error => console.error('Error:', error));
    }

    function getChartColors(count) {
        // 预定义的明亮颜色组合（16种高对比度颜色）
        const brightColors = [
            '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0',
            '#9966FF', '#FF9F40', '#8AC24A', '#EA5545',
            '#F46A9B', '#EF9B20', '#EDBF33', '#87BC45',
            '#27AEEF', '#B33DC6', '#00AEEF', '#E6007E'
        ];

        // 如果需要的颜色少于预定义数量，直接取用
        if (count <= brightColors.length) {
            return brightColors.slice(0, count);
        }

        // 如果需要更多颜色，动态生成
        const colors = [];
        const hueStep = 360 / count;
        for (let i = 0; i < count; i++) {
            const hue = (i * hueStep) % 360;
            colors.push(`hsl(${hue}, 80%, 60%)`);
        }
        return colors;
    }

    // 默认加载第一个图表
    document.addEventListener('DOMContentLoaded', function () {
        showChart('popularCities');
    });
</script>
</body>
</html>